package com.example.websocketdemo.Socket;

import lombok.extern.slf4j.Slf4j;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import java.net.URI;
import java.net.URISyntaxException;

/**
 * @program: basic
 * @description: socket客户端
 * @author: Cloud
 * @create: 2020/11/16 14:57:09
 */
@Slf4j
@Component
public class WebSocketConfig {

    @Bean
    public WebSocketClient webSocketClient() throws URISyntaxException {
        WebSocketClient webSocketClient = new WebSocketClient(new URI("ws://localhost:8090/websocket/test1"),
                new Draft_6455()) {
            @Override
            public void onOpen(ServerHandshake serverHandshake) {
                log.info("[websocket] 连接成功");
            }

            @Override
            public void onMessage(String message) {
                log.info("客户端1,收到消息");
                log.info("{}", message);
            }

            @Override
            public void onClose(int code, String reason, boolean remote) {
                log.info("[websocket] 退出连接");
            }

            @Override
            public void onError(Exception e) {
                log.info("[websocket] 连接错误={}",e.getMessage());
            }
        };
        webSocketClient.connect();
        return webSocketClient;
    }
}
